package com.gack.helper.redis;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 
 * @author ws
 * 2018-8--20
 */
@Component
public class UserActionInfoRedis {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private JedisPool jedisPool;
	@Autowired
	private UserEnterpriseDepartmentPositionRepository userEnterpriseDepartmentPositionRepository;
	
	public long recordChosenEnterpriseId(String userId, String enterpriseId){
		try(Jedis jedis = jedisPool.getResource();){
			return jedis.hset("chosenEnterpriseId", userId, enterpriseId);
		}catch(Exception e){
			logger.error(e.toString());
			return -1;
		}
		
	}
	
	public String getLastChosenEnterpriseId(String userId){
		try(Jedis jedis = jedisPool.getResource();){
			String enterpriseId = jedis.hget("chosenEnterpriseId", userId);
			//若人员不在该上次选择的公司内,则选择人员所在公司中最新创建的公司
			if(StringUtils.isBlank(enterpriseId) || userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(userId, enterpriseId) == 0){
				enterpriseId = userEnterpriseDepartmentPositionRepository.findNewestCreatedEnterprise(userId);
			}
			return StringUtils.isBlank(enterpriseId)?null:enterpriseId;
		}catch(Exception e){
			logger.error(e.toString());
			return null;
		}
	}
	
}
